package com.hqm.web.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hqm.meta.LoginMsg;
import com.hqm.meta.User;
import com.hqm.service.UserService;

@Controller
public class UserController {
	private static final Log logger = LogFactory.getLog(UserController.class);
	 
	@Resource
	private UserService userService; 

	/**
	 * 处理登录请求，验证用户登录表单输入
	 * @param userName
	 * @param password
	 * @return 登录成功返回首页，登录失败停留在登录页
	 */
	@ResponseBody
	@RequestMapping(value = "/api/login", method = RequestMethod.POST)
	public LoginMsg logIn(@RequestParam String userName, 
			@RequestParam String password, HttpSession session) {
		logger.info("doLogIn called");
		
		LoginMsg loginMsg = new LoginMsg();
		try {
			User user = userService.checkUser(userName, password);
			session.setAttribute("user", user);
			loginMsg.setCode(HttpServletResponse.SC_OK);
			loginMsg.setMessage("登录成功");
			loginMsg.setResult(true);
		} catch (Exception e) {
			loginMsg.setCode(HttpServletResponse.SC_ACCEPTED);
			loginMsg.setMessage(e.getMessage());
			loginMsg.setResult(false);
		}
		
		return loginMsg;
	}
	
	/**
	 * 登出，删除session，重定向到首页
	 * @param response
	 * @param sessionStatus
	 * @throws IOException
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public void logOut(HttpServletResponse response,
			HttpSession session) throws IOException {
		logger.info("logout called");
		
		session.invalidate();
		response.sendRedirect("/onlinebussiness");
	}
}
